package com.zhuangjie.coupon.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuangjie.coupon.entity.CouponProduct;
import com.zhuangjie.coupon.mapper.CouponProductMapper;
import com.zhuangjie.coupon.pojo.CouponBatchAndLink;
import com.zhuangjie.coupon.service.CouponProductService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhuangjie
 * @since 2024-02-28
 */
@Service
public class CouponProductServiceImpl extends ServiceImpl<CouponProductMapper, CouponProduct> implements CouponProductService {

    @Cacheable(value = {"coupon-product"}, key = "#root.method.name", sync = true) // sync解决缓存击穿
    @Override
    public List<CouponProduct> queryPlatformProvincialWallet() {
        // 查询平台省级钱包产品列表
        // 先查询产品
        List<CouponProduct> couponProductList = this.list();
        // 建立快查map
        Map<Long, CouponProduct> couponProductMap = couponProductList.stream().collect(Collectors.toMap(CouponProduct::getId, couponProduct -> couponProduct));
        // keys == productIds
        Set<Long> productIds = couponProductMap.keySet();
        if (productIds == null || productIds.isEmpty()) return new ArrayList<>();
        List<CouponBatchAndLink> couponBatchAndLinkList = this.getBaseMapper().queryCouponProductAndLinkList(productIds);
        for (CouponBatchAndLink couponBatchAndLink : couponBatchAndLinkList) {
            CouponProduct couponProduct = couponProductMap.get(couponBatchAndLink.getProductId());
            if (couponProduct == null) continue;
            List<CouponBatchAndLink> couponBatchList = couponProduct.getCouponBatchList();
            if (couponBatchList == null) couponProduct.setCouponBatchList(couponBatchList = new ArrayList<>());
            couponBatchList.add(couponBatchAndLink);
        }
        // 如果产品内无券，该优惠券产品不可显示购买
        couponProductList.removeIf(couponProduct -> couponProduct.getCouponBatchList() == null || couponProduct.getCouponBatchList().isEmpty());
        return couponProductList;
    }

    @Override
    public List<CouponBatchAndLink> queryCouponProductById(Long couponProductId) {
        List<CouponBatchAndLink> couponBatchAndLinkList = this.getBaseMapper().queryCouponProductAndLinkListByProductId(couponProductId);
        if (couponBatchAndLinkList == null ) return new ArrayList<>();
        return couponBatchAndLinkList;
    }

    @CacheEvict(value = "coupon-product",allEntries = true)
    public void updatePlatformProvincialWalletInfo() {
        System.out.println("调用了删除缓存");
    }
}
